package com.sense.feel.login.view

import android.content.Context
import android.content.Intent
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseUser
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import com.linecorp.linesdk.LineProfile
import com.sense.feel.common.global.bean.WebPage
import com.sense.feel.common.utils.*
import com.sense.feel.login.manager.*
import com.sense.feel.login.manager.callback.OnFacebookLoginCallback
import com.sense.feel.login.manager.callback.OnGoogleLoginCallback
import com.sense.feel.login.manager.callback.OnLineLoginCallback
import com.sense.feel.login.model.bean.AreaBean
import com.sense.feel.login.model.bean.PictureCode
import com.sense.feel.login.utils.ReadAssetsJsonUtil
import com.sense.feel.login.vm.*
import com.sense.kukoo.biz_login.R
import com.sense.kukoo.biz_login.databinding.LoginActivityLoginBinding
import com.sense.kukoo.common.config.ConfigManager
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.utils.CountDownerUtil
import com.sense.kukoo.common.utils.KeyBoardUtils
import com.sense.kukoo.common.utils.LiveDataBus
import com.sense.kukoo.common.utils.NetworkTypeUtils
import com.sense.kukoo.common.wiget.VerifiyCodeEditText
import com.sense.kukoo.lib_logger.LoggerManager

import com.sense.kukoo.common.constant.AppConstant
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.constant.H5AddressContant


@Route(path = ARouterUrl.ROUTE_LOGIN_MODULE_LOGIN_ACTIVITY)
class LoginActivity : BaseMvvmActivity<LoginViewModel, LoginActivityLoginBinding>() {
    private var popupWindow: PopupWindow? = null
    private lateinit var areaList: MutableList<com.sense.feel.login.model.bean.AreaBean>
    private var ticket: String? = null
    private var randstr: String? = null
    private var countDownerUtil: CountDownerUtil? = null

    private var TAG = "LoginActivity"
    override fun getLayoutId(): Int = R.layout.login_activity_login

    override fun getViewModelClass(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }


    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.viewModel = mViewModel
        mViewModel.initData()
        //SenseDataAPIUtil.getInstance().reportLoginEvent()
        initThirdLogin()
        areaList = getSenseAreaList("area_phone_code.json", this)
    }

    fun getSenseAreaList(fileName: String, context: Context): MutableList<com.sense.feel.login.model.bean.AreaBean> {
        val jsonStr = ReadAssetsJsonUtil.getJson(fileName, context)
        //Log.d("ReadAssetsJsonUtil==", jsonStr)
        val gson = Gson()
        val type = object : TypeToken<MutableList<com.sense.feel.login.model.bean.AreaBean?>?>() {}.type
        val mAreaBeans = gson.fromJson<MutableList<com.sense.feel.login.model.bean.AreaBean>>(jsonStr, type)
        // 根据拼音为数组进行排序
        //Collections.sort(mAreaBeans, ComparatorPY())
        return mAreaBeans
    }

    private fun initThirdLogin() {
        GoogleLoginManager.initGoogleLoginConfig(this)
        LineLoginManager.initLine()
        FacebookLoginManager.initFacebookLoginConfig(this, object : OnFacebookLoginCallback {
            override fun onSuccess(firebaseUser: FirebaseUser) {
                with(firebaseUser) {
                    var avatar =
                        firebaseUser.photoUrl?.scheme + "://" + firebaseUser.photoUrl?.host + firebaseUser.photoUrl?.path
                    displayName?.let { mViewModel.login(avatar, "Facebook", it, uid) }
                }
            }

            override fun onFail(msg: String) {
                hideLoadingDialog()
                Toast.makeText(this@LoginActivity, msg, Toast.LENGTH_SHORT).show()
            }

            override fun onCancel() {
                Toast.makeText(this@LoginActivity, "用戶已取消", Toast.LENGTH_SHORT).show()
                hideLoadingDialog()
            }
        })
    }

    override fun initStatusBar() {
        ImmersionBar.with(this)
            .transparentStatusBar()  //透明状态栏，不写默认透明色
            .transparentNavigationBar()
            .init()
    }

    override fun initView() {
        setProtocol(8,18)

        //
        /*ConfigManager.instance.getLoginConfig()?: run {
            mViewModel.getConfigInfo()
            return
        }

        // false 直接跳到电话登陆
        if (ConfigManager.instance.getLoginConfig()?.thirdSwitch == false) {
            mBinding.loginOptionLl.visibility = View.INVISIBLE
        } else {
            mBinding.loginOptionLl.visibility = View.VISIBLE
        }*/

        mBinding.loginCodeEnter.setOnFocusChangeListener(OnFocusChangeListener { view, hasFocus ->
            if (!hasFocus) {
                val manager =
                    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager?.hideSoftInputFromWindow(
                    view.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        })
        mBinding.phoneEt.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                mBinding.verifyCodeTv.isEnabled = !TextUtils.isEmpty(s)
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })
    }

    override fun responseVM(action: Int) {
        when (action) {
            ACTION_TO_PHONE_LOGIN -> {
                /*ARouter.getInstance().build(ARouterUrl.ROUTE_LOGIN_MODULE_PHONE_LOGIN_ACTIVITY)
                    .navigation()*/
            }
            ACTION_TO_FACEBOOK_LOGIN -> {
                FacebookLoginManager.login(this)
            }
            ACTION_TO_LINE_LOGIN -> {
                LineLoginManager.lineLogin(this)
            }
            ACTION_TO_GOOGLE_LOGIN -> {
                GoogleLoginManager.signIn(this)
            }
            ACTION_TO_ENTER_APP -> {
                ToastUtils.showToast("go to main")
                /*ARouter.getInstance().build(ARouterUrl.ROUTE_APP_MODULE_MAIN_ACTIVITY)
                    .navigation()*/

            }
            ACTION_TO_INTEREST_PAGE -> {
                val model = WebPage()
                model.url = H5AddressContant.getInterest()
                LoggerManager.e(TAG, " model.url=" + H5AddressContant.getInterest())
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                    .withParcelable(ConstantConfig.ARG1, model)
                    .navigation()

                finish()
            }
            ACTION_TO_CLOSE -> {
                finish()
            }
            ACTION_PHONE_LOGIN_SUCCESS_TO_HOME -> {
                LiveDataBus.get().with(AppConstant.LOGIN).postValue(AppConstant.LOGIN)
                ToastUtils.showToast("go to main")
                /*ARouter.getInstance().build(ARouterUrl.ROUTE_APP_MODULE_MAIN_ACTIVITY)
                    .navigation()*/
                finish()
            }
            ACTION_UPDATE_CONFIG_SUCCESS -> {
                initView()
            }
            ACTION_SELECT_COUNTRY -> {
                showAreaPop()
            }
            ACTION_PHONE_LOGIN_TO_PICTURE_VERIFY -> {
                if (!mBinding.protocolCb.isChecked) {
                    ToastUtils.showToast(getString(R.string.login_privacy))
                    KeyBoardUtils.closeKeybord(mBinding.loginCodeEnter,this)
                    return
                }
                mBinding.protocolCb.isEnabled = false
                var intent = Intent(this, PictureVerifyActivity::class.java)
                if (NetworkTypeUtils.getNetWrokType(this).equals("null")) {
                    ToastUtils.showToast(getString(R.string.wrong_phone_number))
                    return
                }
                startActivityForResult(intent, PICTURE_VERIFY_ACTIVITY_REQUEST_CODE)
            }
            // 獲取驗證碼成功介面
            ACTION_PHONE_LOGIN_GETCODE_SUCCESS -> {
                hideLoadingDialog()
                mBinding.loginPhoneLl.visibility = View.GONE
                mBinding.loginVerifiyLl.visibility = View.VISIBLE
                mBinding.closeIv.visibility = View.GONE
                mBinding.backIv.visibility = View.VISIBLE
                mBinding.verifyCodeTv.visibility = View.GONE
                mBinding.loginOptionLl.visibility = View.GONE
                mBinding.protocolCb.visibility = View.GONE
                mBinding.loginProtocolTv.visibility = View.GONE
                mBinding.verifyCodeTv.text = getString(R.string.login)
                mBinding.loginCodeEnter.requestFocus()
                mBinding.loginCodeEnter.postDelayed(Runnable {
                    mBinding.loginCodeEnter.requestFocus()
                    val manager =
                        this.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    manager?.showSoftInput(mBinding.loginCodeEnter, 0)
                }, 300)
                mBinding.alreadySendCodeTv.setText(String.format(getString(R.string.login_already_send),mViewModel.mAreaLiveData.value,mViewModel.mPhoneLiveData.value))
//                Toast.makeText(applicationContext,"請手動輸入",Toast.LENGTH_LONG).show()
                doCountDownTimer()
                mBinding.verifyCodeTv.isEnabled = false
                mBinding.loginCodeEnter.setOnPasswordListener(object : VerifiyCodeEditText.OnPasswordListener {
                    override fun onSuccess(text: String?) {
                        if (mBinding.loginPhoneLl.visibility == VISIBLE) {
                            return
                        }
                        mBinding.verifyCodeTv.isEnabled = !TextUtils.isEmpty(text) && text?.length ?: 0 == 4
                        mViewModel.loginWithPhone()
                    }

                    override fun onEnter(text: String?) {
                        if (mBinding.loginPhoneLl.visibility == VISIBLE) {
                            return
                        }
                        mBinding.verifyCodeTv.isEnabled = !TextUtils.isEmpty(text) && text?.length ?: 0 == 4
                    }
                })
            }
            // 返回到手機號碼輸入介面
            ACTION_PHONE_LOGIN_GETCODE_BACK -> {
                mBinding.loginPhoneLl.visibility = View.VISIBLE
                mBinding.loginVerifiyLl.visibility = View.GONE
                mBinding.closeIv.visibility = View.VISIBLE
                mBinding.backIv.visibility = View.GONE
                mBinding.verifyCodeTv.text = getString(R.string.login_phone_login_get_verify_code)
                mBinding.verifyCodeTv.visibility = View.VISIBLE
                mBinding.loginOptionLl.visibility = View.VISIBLE
                mBinding.protocolCb.visibility = View.VISIBLE
                mBinding.loginProtocolTv.visibility = View.VISIBLE
                mViewModel.mCodeLiveData.postValue("")
                countDownerUtil?.cancel()
                mBinding.loginCodeDownCount.text = getString(R.string.login_need_some_help)
                mBinding.verifyCodeTv.isEnabled = true
                mBinding.protocolCb.isEnabled = true
            }
            ACTION_PHONE_REGISTER_SUCCESS_TO_INTEREST -> {
                val model = WebPage()
                model.url = H5AddressContant.getInterest()
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                    .withParcelable(ConstantConfig.ARG1, model)
                    .navigation()
                LiveDataBus.get().with(AppConstant.LOGIN).postValue(AppConstant.LOGIN)
                finish()
            }

            ACTION_PHONE_LOGIN_GETCODE_FAILED -> {
                hideLoadingDialog()
                mBinding.verifyCodeTv.isEnabled = true
                ToastUtils.showToast(getString(R.string.network_was_wrong))
            }
            ACTION_SHOW_NEED_HELP -> {
                val dialog = LoginHelpDialog()
                dialog?.setStyle(
                    DialogFragment.STYLE_NORMAL,
                    R.style.dialog_full_screen
                )
                dialog.show(supportFragmentManager,LoginHelpDialog::class.java.name)
            }

            ACTION_PHONE_LOGIN_FAILED -> {
                hideLoadingDialog()
                ToastUtils.showToast(getString(R.string.network_was_wrong))
            }
            ACTION_PHONE_WRONG_NO_FAILED -> {
                hideLoadingDialog()
                mBinding.verifyCodeTv.isEnabled = true
                ToastUtils.showToast(getString(R.string.wrong_phone_number))
            }
        }
    }

    private fun showAreaPop() {
        if (popupWindow == null) {
            val view = View.inflate(this, R.layout.login_list_pop, null)
            var recyclerView = view.findViewById<View>(R.id.lv_content) as RecyclerView
            setAreaList(recyclerView)
            popupWindow = PopupWindow(
                view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            popupWindow?.isFocusable = true
            popupWindow?.isOutsideTouchable = true
            popupWindow?.showAsDropDown(mBinding.areaCodeTv)
        } else {
            popupWindow?.showAsDropDown(mBinding.areaCodeTv)
        }
    }

    private fun setAreaList(recyclerView: RecyclerView) {
        var linearLayoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = linearLayoutManager
        var adapter = object : BaseQuickAdapter<AreaBean, BaseViewHolder>(
            R.layout.login_item_area,
            areaList
        ) {
            override fun convert(holder: BaseViewHolder, item: AreaBean) {
                holder.setText(R.id.txt_name, item.tw)
                holder.setText(R.id.txt_num, item.code.toString())
                holder.itemView.setOnClickListener {
                    mBinding.areaCodeTv.text = item.code.toString()
                    popupWindow?.dismiss()
                }
            }
        }
        recyclerView.adapter = adapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LoggerManager.e(TAG, "resultCode=" + resultCode)
        LoggerManager.e(TAG, "requestCode=" + requestCode)
        LoggerManager.e(TAG, "data=" + data?.data)
        LoggerManager.e(TAG, "extras=" + data?.extras.toString())
        if (requestCode == GOOGLE_REQUEST_CODE) {
            googleLogin(data)
        } else if (requestCode == FACEBOOK_RESULT_CODE) {
            FacebookLoginManager.onActivityResult(requestCode, resultCode, data)
        } else if (requestCode == LineLoginManager.LINE_REQUEST_CODE) {
            LineLoginManager.lineLoginCallBack(requestCode, data, object : OnLineLoginCallback {
                override fun onSuccess(lineProfile: LineProfile) {
                    with(lineProfile) {
                        var avatar =
                            lineProfile.pictureUrl?.scheme + "://" + lineProfile.pictureUrl?.host + lineProfile.pictureUrl?.path
                        mViewModel.login(avatar, "Line", displayName, userId)
                    }
                }

                override fun onFail(msg: String) {
                    hideLoadingDialog()
                }

                override fun onCancel() {
                    hideLoadingDialog()
                }

            })
            //獲取驗證碼成功
        } else if (requestCode == PICTURE_VERIFY_ACTIVITY_REQUEST_CODE) {
            if ( resultCode == PICTURE_VERIFY_ACTIVITY_RESULT_CODE ) {
                var pictureCode = data?.getSerializableExtra("pictureCode") as PictureCode
                ticket = pictureCode.ticket
                randstr = pictureCode.randstr
                LoggerManager.e(TAG, "ticket=" + ticket)
                LoggerManager.e(TAG, "randstr=" + randstr)
                mViewModel.getVerifyCode(randstr ?: "", ticket ?: "")
                mBinding.verifyCodeTv.isEnabled = false
                showLoadingDialog()
            } else {
                mBinding.protocolCb.isEnabled = true
            }
        }
    }

    private fun doCountDownTimer() {
        countDownerUtil = CountDownerUtil(this, 60000, 1000)
        countDownerUtil?.start()
        countDownerUtil?.setOnFinishListenrer(object : CountDownerUtil.OnFinishListener {
            override fun onFinish() {
                val str = getString(R.string.login_reget_code)
                val span = SpannableString(str)
                span.setSpan(ForegroundColorSpan(resources.getColor(R.color.common_text_red)),
                    0,
                    str.length,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                mBinding.loginCodeDownCount.text = span
            }

            override fun onTick(millisUntilFinished: Long) {
                val str = getString(R.string.login_wait_code)
                val mCountDownSeconds = millisUntilFinished / 1000
                var lastIndex = 0
                if (mCountDownSeconds > 9) {
                    lastIndex = 12
                } else {
                    lastIndex = 11
                }
                val ss = String.format(str,mCountDownSeconds)
                val span = SpannableString(ss)
                span.setSpan(ForegroundColorSpan(resources.getColor(R.color.common_text_red)),
                    8,
                     lastIndex,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                mBinding.loginCodeDownCount.text = span

            }
        })
    }

    private fun googleLogin(data: Intent?) {
        try {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            val account = task.getResult(ApiException::class.java)
            LoggerManager.e(TAG, "firebaseAuthWithGoogle_id=" + account.id)
            LoggerManager.e(TAG, "firebaseAuthWithGoogle_Token=" + account.idToken)
            GoogleLoginManager.firebaseAuthWithGoogle(
                this,
                account,
                object : OnGoogleLoginCallback {
                    override fun onSuccess(firebaseUser: FirebaseUser) {
                        with(firebaseUser) {
                            var avatar =
                                firebaseUser.photoUrl?.scheme + "://" + firebaseUser.photoUrl?.host + firebaseUser.photoUrl?.path
                            displayName?.let { mViewModel.login(avatar, "Google", it, uid) }
                        }
                    }

                    override fun onFail(msg: String) {
                        LoggerManager.e(TAG, "onFail=" + msg)
                        hideLoadingDialog()
                    }

                })
        } catch (e: ApiException) {
            LoggerManager.e(TAG, "Exception=" + e.message)
            hideLoadingDialog()
        }
    }


    private fun setProtocol(useStart: Int, useEnd: Int) {
        val spannableString = SpannableString(getString(R.string.login_privacy))
        //设置文字的前景色
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                if (widget is TextView) {
                    widget.highlightColor = resources.getColor(android.R.color.transparent)
                }
                val model = WebPage()
                model.url = H5AddressContant.getPrivacy()
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_LOGIN_MODULE_WEB_ACTIVITY)
                    .withParcelable(ConstantConfig.ARG1, model)
                    .navigation()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
            }
        }, useStart, useEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.common_blue_high_light)),
            useStart,
            useEnd,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.loginProtocolTv.text = spannableString
        mBinding.loginProtocolTv.movementMethod = LinkMovementMethod.getInstance()
    }

    override fun onResume() {
        super.onResume()
        LoggerManager.e(TAG, "onResume")
        /*AppStatisticsUtils.saveStatistics(0, AppStatisticsEventType.LOGIN_PAGE)*/
    }

}